#!/usr/bin/env node

const { con, Result } = require('./common');
const { Getusersig } = require('./tim_mod.js');
let Admin_gets = async () => {
	let res = new Result()
	let sql = `select * from admin`
	let [rows] = await con.execute(sql)

	res.data = rows
	return res
}
let Admin_get_slg = async (admin_phone, admin_password, time) => {
	let res = new Result()
	let sql = `select * from admin where admin_phone = '${admin_phone}'`
	let [rows] = await con.execute(sql)

	if (rows.length === 0) {
		res.code = 40001
		res.msg = '用户不存在'
	} else if (rows[0].admin_password !== admin_password) {
		res.code = 40002
		res.msg = '密码错误'
	} else {
		let sql1 = `update admin set admin_last_time = '${time}' where admin_phone = ${admin_phone}`;
		let [rows1] = await con.execute(sql1);
		res.data = rows[0];
	}
	return res
}
let Admin_delete = async (admin_id, admin_id2, admin_password) => {
	let res = new Result();
	let sql = `select * from admin where admin_id = ${admin_id} and admin_password = '${admin_password}'`;
	let [rows] = await con.execute(sql);
	if (rows.length == 1) {
		let sql1 = `delete from admin where admin_id = ${admin_id2}`;
		let [rows1] = await con.execute(sql1);
	} else {
		res.msg = '密码错误';
		res.code = 40002;
	}
	return res;
}
let Admin_create = async (admin_id, password, admin_name, admin_position, admin_phone, admin_email, admin_password, password_confim) => {
	let res = new Result();
	let date = new Date();
	let time = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
	let admin_sig = Getusersig(admin_phone);
	let sql = `select * from admin where admin_id = ${admin_id} and admin_password = '${password}'`;
	let [rows] = await con.execute(sql);
	if (rows.length == 1) {
		if (admin_password == password_confim) {
			let sql1 = `select * from admin where admin_phone = ${admin_phone}`;
			let [rows1] = await con.execute(sql1);
			if (rows1.length == 0) {
				let sql3 = `select * from admin`;
				let [rows3] = await con.execute(sql3);
				let sql2 = `insert into admin values(${rows3[rows3.length - 1].admin_id + 1},'${admin_name}','${admin_position}',${admin_phone},'${admin_email}','${admin_password}',NULL,'${admin_sig}','${time}',false)`;
				let [rows2] = await con.execute(sql2);
			} else {
				res.code = 40004;
				res.msg = '该手机号已被注册';
			}
		} else {
			res.code = 40003;
			res.msg = '两次输入密码不一致';
		}
	} else {
		res.code = 40002;
		res.msg = '密码错误';
	}
	return res;
}
module.exports = { Admin_create, Admin_gets, Admin_get_slg, Admin_delete };
